package com.cfs.ipc;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cfs.io.DataOutputBuffer;

public class Client {
	
	private static Log LOG = LogFactory.getLog(Client.class);
	
	private String host;
	private int port;
	private Socket socket;
	private DataInputStream				in;
	private DataOutputStream			out;
	
	public Client(String host, int port) {
		this.host = host;
		this.port = port;
		init();
	}
	
	private void init() {
		try {
			socket = new Socket(host, port);
			this.in = new DataInputStream(socket.getInputStream());
			this.out = new DataOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void invoke(Invocation invocation)  {
		try {
			DataOutputBuffer buffer = new DataOutputBuffer();
			invocation.write(buffer);
			int bufLen = buffer.getLength();
			out.writeInt(bufLen);
			out.write(buffer.getData(), 0, bufLen);
			LOG.info("1.client sendBuffer length: " + bufLen);
			
			
			int length = in.readInt();
			byte[] receiveBuffer = new byte[length];
			int position = 0;
			int hasRead = 0;
			
//			while((position = in.read(receiveBuffer, 0, receiveBuffer.length)) != -1) {
//				hasRead += position;
//				if(hasRead >= length) {
//					break;
//				}
//			}
			LOG.info("4.client receiveBuffer length: " + length);
			
			Invocation invo = new Invocation();
			invo.readFields(in);
			System.out.println(invo);
			
//			byte[] sendBuffer = IOUtils.toByte(invocation);
//			out.write(sendBuffer);
//			LOG.info("1.client sendBuffer length: " + sendBuffer.length);
//			
//			int length = in.readInt();
//			byte[] receiveBuffer = new byte[length];
//			int position = 0;
//			byte[] buffer = new byte[length];
//			int hasRead = 0;
//			
//			while((position = in.read(buffer, 0, buffer.length)) != -1) {
//				hasRead += position;
//				if(hasRead == length) {
//					break;
//				}
//			}
//			LOG.info("4.client receiveBuffer length: " + length);
//			byte[] newBuffer = new byte[length - 4];
//			System.arraycopy(buffer, 4, newBuffer, 0, newBuffer.length);
//			Invocation invoc = (Invocation) IOUtils.toObject(newBuffer);
//			invocation.setResult(invoc.getResult());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setHost(String host) {
		this.host = host;
	}
	
	public String getHost() {
		return host;
	}
	
	public void setPort(int port) {
		this.port = port;
	}
	
	public int getPort() {
		return port;
	}
	
}
